<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Table, Rate, Empty } from 'ant-design-vue';
import type { MakeupServiceOrder } from '#/api/wedding';
import { getArtistRatings } from '#/api/wedding';
import dayjs from 'dayjs';

const props = defineProps<{
  artistCode: string;
}>();

const loading = ref(false);
const ratings = ref<MakeupServiceOrder[]>([]);
const total = ref(0);
const pagination = ref({
  current: 1,
  pageSize: 10,
});

const columns = [
  { 
    title: '客户姓名', 
    dataIndex: 'customerName', 
    key: 'customerName', 
    width: 120 
  },
  { 
    title: '评分', 
    key: 'rating', 
    width: 150,
    slots: { customRender: 'rating' }
  },
  { 
    title: '评价内容', 
    dataIndex: 'comment', 
    key: 'comment',
    customRender: ({ text }: any) => text || '客户未留言',
  },
  { 
    title: '服务时间', 
    dataIndex: 'serviceTime', 
    key: 'serviceTime', 
    width: 180,
    customRender: ({ text }: any) => dayjs(text).format('YYYY-MM-DD HH:mm'),
  },
  { 
    title: '评价时间', 
    dataIndex: 'createTime', 
    key: 'createTime', 
    width: 180,
    customRender: ({ text }: any) => dayjs(text).format('YYYY-MM-DD HH:mm'),
  },
];

const loadRatings = async () => {
  loading.value = true;
  try {
    const data = await getArtistRatings(props.artistCode, {
      pageNo: pagination.value.current,
      pageSize: pagination.value.pageSize,
    });
    ratings.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  loadRatings();
};

// 计算平均分和星级分布
const averageRating = ref(0);
const ratingDistribution = ref<Record<number, number>>({
  5: 0,
  4: 0,
  3: 0,
  2: 0,
  1: 0,
});

const calculateStatistics = () => {
  if (ratings.value.length === 0) return;
  
  const distribution: Record<number, number> = { 5: 0, 4: 0, 3: 0, 2: 0, 1: 0 };
  let totalScore = 0;
  
  ratings.value.forEach(rating => {
    if (rating.rating) {
      const score = Math.floor(rating.rating);
      distribution[score] = (distribution[score] || 0) + 1;
      totalScore += rating.rating;
    }
  });
  
  averageRating.value = ratings.value.length > 0 
    ? Number((totalScore / ratings.value.length).toFixed(1))
    : 0;
  ratingDistribution.value = distribution;
};

onMounted(() => {
  loadRatings();
});
</script>

<template>
  <div>
    <!-- 评分统计 -->
    <div class="mb-6 p-4 bg-gray-50 rounded">
      <div class="grid grid-cols-2 gap-4">
        <div class="text-center">
          <div class="text-3xl font-bold text-orange-500 mb-2">
            {{ averageRating }}
          </div>
          <Rate :value="averageRating" disabled allow-half />
          <div class="text-sm text-gray-500 mt-1">
            基于 {{ total }} 条评价
          </div>
        </div>
        <div>
          <div class="space-y-1">
            <div v-for="star in [5, 4, 3, 2, 1]" :key="star" class="flex items-center">
              <span class="w-12 text-sm">{{ star }}星</span>
              <div class="flex-1 mx-2 bg-gray-200 rounded-full h-2">
                <div 
                  class="bg-orange-400 h-2 rounded-full"
                  :style="{ 
                    width: total > 0 
                      ? `${(ratingDistribution[star] / total * 100)}%` 
                      : '0%' 
                  }"
                ></div>
              </div>
              <span class="w-12 text-sm text-gray-600">
                {{ ratingDistribution[star] || 0 }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 评价列表 -->
    <Table
      :dataSource="ratings"
      :columns="columns"
      :loading="loading"
      :pagination="{
        current: pagination.current,
        pageSize: pagination.pageSize,
        total: total,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleTableChange"
      size="small"
    >
      <template #rating="{ record }">
        <div v-if="record.rating">
          <Rate :value="record.rating" disabled allow-half />
          <span class="ml-2 text-sm text-gray-500">{{ record.rating }}分</span>
        </div>
        <span v-else class="text-gray-400">未评分</span>
      </template>
    </Table>

    <Empty v-if="!loading && ratings.length === 0" description="暂无评价" />
  </div>
</template>
